/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import ManagerInfoFile.FileInfo;
import SocKet.Client;
import SocKet.Server;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
public class frmBittorentLikes extends javax.swing.JFrame {

    protected Client client;
    protected Server server;
    public frmBittorentLikes() {
        initComponents();
        //server = new Server();
        //server.ReceiverBroadCast();
        client = new Client();
        client.ReadDataNode();
               
        //server = new Server();
        //server.ReceiverBroadCast();
        
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFrame1 = new javax.swing.JFrame();
        jTabbedPane6 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        btnNewFile = new javax.swing.JButton();
        btnBatDau = new javax.swing.JButton();
        btnTamNgung = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        btnFileChink = new javax.swing.JButton();
        btnChiaSeFile = new javax.swing.JButton();

        javax.swing.GroupLayout jFrame1Layout = new javax.swing.GroupLayout(jFrame1.getContentPane());
        jFrame1.getContentPane().setLayout(jFrame1Layout);
        jFrame1Layout.setHorizontalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 400, Short.MAX_VALUE)
        );
        jFrame1Layout.setVerticalGroup(
            jFrame1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 300, Short.MAX_VALUE)
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        btnNewFile.setText("File Mới");
        btnNewFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNewFileActionPerformed(evt);
            }
        });

        btnBatDau.setText("Bắt đầu");

        btnTamNgung.setText("Tạm ngưng");
        btnTamNgung.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnTamNgungActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(btnNewFile, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnBatDau, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnTamNgung, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnNewFile)
                    .addComponent(btnBatDau)
                    .addComponent(btnTamNgung))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 273, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        jTabbedPane6.addTab("Tải Xuống", jPanel1);

        jTable2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jTable2);

        btnFileChink.setText("Chọn tập tin chunk");
        btnFileChink.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFileChinkActionPerformed(evt);
            }
        });

        btnChiaSeFile.setText("Chọn File");
        btnChiaSeFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnChiaSeFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(btnFileChink)
                .addGap(28, 28, 28)
                .addComponent(btnChiaSeFile, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 618, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnFileChink)
                    .addComponent(btnChiaSeFile))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 275, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTabbedPane6.addTab("Chia Sẻ", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane6)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jTabbedPane6)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
    private void btnTamNgungActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnTamNgungActionPerformed
      
    }//GEN-LAST:event_btnTamNgungActionPerformed

    private void btnNewFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNewFileActionPerformed
      
        JFileChooser fileDlg = new JFileChooser();
        fileDlg.addChoosableFileFilter(new FileNameExtensionFilter("File Torrent (*.torrent)", "torrent"));
        if (fileDlg.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) 
        { 
            String filename = fileDlg.getSelectedFile().getAbsolutePath();
            String file = fileDlg.getSelectedFile().getName();
            String[] strTemp = file.split("[.]");
            if(!strTemp[1].equals("torrent") )
            {
                JOptionPane.showMessageDialog(this, "Vui lòng chọn file *.Torrent"+"asd"+strTemp[1].toString());
                return;
            }
            client.ReadDataTorrent(filename);
            client.SendBroadCast();
        }
    }//GEN-LAST:event_btnNewFileActionPerformed

    private void btnChiaSeFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnChiaSeFileActionPerformed
        
        JFileChooser fileDlg = new JFileChooser();
        if (fileDlg.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) 
        { 
            String urlFileName = fileDlg.getSelectedFile().getAbsolutePath();
            String filName =fileDlg.getSelectedFile().getName();
            
            FileInfo fileInfo = new FileInfo();
            fileInfo.SetTenFile(filName);
            if(fileInfo.DocDuLieuTuFile(urlFileName));
                fileInfo.GhiFileTorrent(fileInfo.GetTenFile());
            JOptionPane.showMessageDialog(this, "Chia Sẻ File Thành Công");

        }
    }//GEN-LAST:event_btnChiaSeFileActionPerformed

    private void btnFileChinkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFileChinkActionPerformed
        
        JFileChooser fileDlg = new JFileChooser();
        fileDlg.addChoosableFileFilter(new FileNameExtensionFilter("File Chunk (*.chunk)", "chunk"));
        if (fileDlg.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) 
        { 
            String filename = fileDlg.getSelectedFile().getAbsolutePath();
            String file = fileDlg.getSelectedFile().getName();
            String[] strTemp = file.split("[.]");
            if(!strTemp[1].equals("chunk") )
            {
                JOptionPane.showMessageDialog(this, "Vui lòng chọn file *.chunk"+"asd"+strTemp[1].toString());
                return;
            }
            InputStream input = null;
            OutputStream output = null;
            try {

                input = new FileInputStream(new File(filename));
                output = new FileOutputStream(new File("./Data/Share/"+file));
                
                byte[] buf = new byte[1024];
                int bytesRead;
                while ((bytesRead = input.read(buf)) > 0) {
                    output.write(buf, 0, bytesRead);
                }
                input.close();
                output.close();
                
            } catch(FileNotFoundException ex){
                System.out.println("Lỗi - Không tim thấy file "+ex.getMessage());
            } catch(IOException io){
                System.out.println("Lỗi - Không đọc được File "+io.getMessage());
            }
            JOptionPane.showMessageDialog(this, "Chia Sẻ File Chunk Thành Công");
        }
    }//GEN-LAST:event_btnFileChinkActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmBittorentLikes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmBittorentLikes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmBittorentLikes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmBittorentLikes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmBittorentLikes().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnBatDau;
    private javax.swing.JButton btnChiaSeFile;
    private javax.swing.JButton btnFileChink;
    private javax.swing.JButton btnNewFile;
    private javax.swing.JButton btnTamNgung;
    private javax.swing.JFrame jFrame1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTabbedPane jTabbedPane6;
    private javax.swing.JTable jTable1;
    private javax.swing.JTable jTable2;
    // End of variables declaration//GEN-END:variables
}
